package com.hzqy.service.hqjc;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hzqy.persistence.dao.epg.AcIntegralDao;
import com.hzqy.persistence.dao.epg.HappyDao;
import com.hzqy.service.epg.AcIptvListServiceBean;
import com.hzqy.service.epg.epgCommonService;
import com.hzqy.web.ac.epg.HappyAction;
import com.hzqy.web.vo.activity.ActivityVoteUserVo;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.MD5;
import com.hzqy.persistence.dao.activity.ActivityModelDao;
import com.hzqy.persistence.dao.hqjc.ActivityDao;
import com.hzqy.service.activity.ActivityModelServiceBean;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.AcLotteryVo;
import com.hzqy.web.vo.AcRecordVo;
import com.hzqy.web.vo.AcWinningVo;
import com.hzqy.web.vo.PmsUserVo;
import com.hzqy.web.vo.activity.AcContentActionVo;
import com.hzqy.web.vo.activity.ActivityAwardVo;

import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.AcGameVo;

@Service
public class ActivityServiceBean extends GenericServiceBean<PmsUserVo,ActivityDao, Integer>{
	private static final long serialVersionUID = 1L;
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private ActivityDao activityDao;

	@Resource
	private ActivityModelDao activityModelDao;

	@Resource
	private ActivityModelServiceBean activityModelServiceBean;
	@Resource
	private HappyDao happyDao;
	@Resource
	private epgCommonService epgCoService;
	@Resource
	private AcIntegralDao acIntegralDao;
	@Resource
	private AcIptvListServiceBean iptvServiceBean;

	@Override
	public ActivityDao getEntityDao() {
		return activityDao;
	}

	public  Integer getDaTi(AcRecordVo acr){
		System.out.println(""+acr.getX_lwj_uesr_id()+"99999999"+acr.getX_lwj_activityid());
		return activityDao.selectDaTi(acr);
	}
	public  Integer getDuiDuiPeng(AcRecordVo acr){
		System.out.println(""+acr.getX_lwj_uesr_id()+"99999999"+acr.getX_lwj_activityid()+acr.getX_lwj_date());

		return activityDao.selectDuiDuiPeng(acr);
	}
	public Map<String,String> getLotteryResult(AcWinningVo awv){
		LOG.debug("----------进入抽奖service----------");
		String code = MD5.encrypt32(awv.getF_awl_activityid()+awv.getF_awl_serverid());

		String url = "http://172.24.1.18:9094/actict-front/open/lottery/apply.do?activityId="+awv.getF_awl_activityid()+"&account="+awv.getF_awl_serverid()+"&code="+code;
		LOG.debug("抽奖url:"+url);

		String result="";
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		Map<String,String> map = new HashMap<String, String>();
		try{
			URL urlStr = new URL(url);
			HttpURLConnection con = (HttpURLConnection) urlStr.openConnection();
			con.setDoOutput(true);
			con.setRequestMethod("GET");
			con.setRequestProperty("version", "1.0");
			con.setRequestProperty("Content-Type", "text/xml");
			con.setRequestProperty("Pragma", "no-cache");
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setConnectTimeout(10000);
			con.setReadTimeout(10000);
			is = con.getInputStream();
			isr = new InputStreamReader(is, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			for (line = br.readLine(); line != null; line = br.readLine()) {
				result+=line;
			}
			LOG.debug("----------抽奖结果result:"+result+"----------");
			JSONObject resultJson = JSONObject.parseObject(result);
			map.put("result", resultJson.get("result").toString());
			//map.put("result", "0");
			map.put("msg", resultJson.get("msg").toString());
			if(resultJson.get("result").equals("0")){
				LOG.debug("-----------中奖-------------");
				map.put("awardId", resultJson.get("awardId").toString());
				map.put("awardLevel", resultJson.get("awardLevel").toString());
				map.put("awardName", resultJson.get("awardName").toString());
			}
		}catch(Exception e){
			LOG.error("返回抽奖结果异常：",e);
		}finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (isr != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (br != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		LOG.debug("----------抽奖结果service:"+map.get("msg")+":"+map.get("awardName")+"----------");
		return map;
	}

	public String getDiscount(String serverid,String discount){
		LOG.debug("----------获取折扣service----------");
		String result="";
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br =null;
		OutputStreamWriter out=null;
		try{
			URL urlStr = new URL("http://172.24.1.8:8081/admin/system/rand/discount.do");
			URLConnection con = urlStr.openConnection();
			con.setDoOutput(true);
			con.setRequestProperty("version", "1.0");
			con.setRequestProperty("Content-Type", "text/xml");
			con.setRequestProperty("Pragma", "no-cache");
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setConnectTimeout(10000);
			con.setReadTimeout(10000);
			out = new OutputStreamWriter(con.getOutputStream());
			StringBuilder sb = new StringBuilder();
			sb.append("<?xml version='1.0' encoding='UTF-8'?>");
			sb.append("<ROOT>");
			sb.append("<Itv_Account>"+serverid+"</Itv_Account>");
			sb.append("<Disc_Num>"+discount+"</Disc_Num>");
			sb.append("<Channel_Num>guangd</Channel_Num>");
			sb.append("</ROOT>");
			String xmlInfo = sb.toString();
			out.write(new String(xmlInfo.getBytes("UTF-8")));
			out.flush();
			//out.close();
			is = con.getInputStream();
			isr = new InputStreamReader(is,"UTF-8");
			br = new BufferedReader(isr);
			//BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = "";
			for (line = br.readLine(); line != null; line = br.readLine()) {
				LOG.debug("----------获取折扣结果line:"+line+"----------");
				result+=line;
			}
		}catch(Exception e){
			LOG.error("折扣码获取异常：",e);
		}finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		return result;
	}

	public Map<String,String> xmlInfo(String result){
		Map<String,String> map = new HashMap<String,String>();
		try{
			SAXReader reader = new SAXReader();
			// 定义一个文档
			Document document = null;
			//将字符串转换为
			document = reader.read(new ByteArrayInputStream(result.getBytes("UTF-8")));
			// 得到xml的根节点(message)
			Element root = document.getRootElement();
			//定义子循环体的变量
			Iterator<Element> resultInfos = root.elementIterator();

			while (resultInfos.hasNext()) {
				Element ticket = (Element) resultInfos.next();
				Iterator<Element> tickets = ticket.elementIterator(); // 获取子节点bbbb下的子节点cccc
				while(tickets.hasNext()){
					Element info = tickets.next();
					map.put(info.getName(), info.getText());
					LOG.debug(info.getName()+":"+info.getText());
				}
			}

		}catch(Exception e){
			LOG.error("抽奖XML解析异常：",e);
		}
		return map;
	}

	public Map<String,String> xmlInfoDiscount(String result){
		Map<String,String> map = new HashMap<String,String>();
		try{
			SAXReader reader = new SAXReader();
			// 定义一个文档
			Document document = null;
			//将字符串转换为
			document = reader.read(new ByteArrayInputStream(result.getBytes("UTF-8")));
			// 得到xml的根节点(message)
			Element root = document.getRootElement();
			//定义子循环体的变量
			Element ticket=null;

			Iterator<Element> tickets = null;

			tickets = root.elementIterator();

			while(tickets.hasNext()){
				ticket = tickets.next();
				map.put(ticket.getName(), ticket.getText());
			}
		}catch(Exception e){
			LOG.error("获取折扣XML解析异常：",e);
		}
		return map;
	}

	public int insertLottery(AcLotteryVo alv) {
		int flag = 0;
		if(alv==null) {
			flag = -1;
		}
		if(flag ==0) {
			activityDao.insertLottery(alv);
			return 1;
		}
		return flag;
	}
	public int insertLotteryRecord(AcLotteryVo alv) {
		int flag = 0;
		if(alv==null) {
			flag = -1;
		}
		if(flag ==0) {
			activityDao.insertLotteryRecord(alv);
			return 1;
		}
		return flag;
	}

	public int updateLottery(AcLotteryVo alv) {
		int flag = 0;
		if(alv==null) {
			flag = -1;
		}
		if(flag ==0) {
			flag = activityDao.updateLottery(alv);
		}
		return flag;
	}
	public  Integer updateCount(AcLotteryVo alv){
		return activityDao.updateWinningCoun(alv);
	}
	public int selectLotteryCount(AcLotteryVo alv) {
		int results = activityDao.selectLotteryCount(alv);
		return results;
	}

	public int selectWinningCount(AcWinningVo awv) {
		int results = activityDao.selectWinningCount(awv);
		return results;
	}
	public AcRecordVo selectRecord(AcRecordVo arv) {
		AcRecordVo results = activityDao.selectRecord(arv);
		return results;
	}
	public Integer selectLottery(AcLotteryVo alv) {
		return activityDao.selectLotteryNum(alv);
	}

	public AcWinningVo selectWinning(AcWinningVo awv) {
		AcWinningVo results = activityDao.selectWinning(awv);
		return results;
	}

	public int insertWinningList(AcWinningVo awv) {
		int flag = 0;
		if(awv==null) {
			flag = -1;
		}
		if(flag ==0) {
			awv = reChangeData(awv);
			if(awv.getF_awl_type() == null ){
				awv.setF_awl_type("0");
			}
			activityDao.insertWinningList(awv);
			return 1;
		}
		return flag;
	}

	public int updateWinning(AcWinningVo awv) {
		int flag = 0;
		if(awv==null) {
			flag = -1;
		}
		if(flag ==0) {
			awv = reChangeData(awv);
			flag = activityDao.updateWinning(awv);
		}
		return flag;
	}
	public AcWinningVo reChangeData(AcWinningVo awv){
		Decoder decoder = Base64.getDecoder();
		Encoder encoder = Base64.getEncoder();
		String decode = "";
		String encode = "";
		try {
			byte[] bytes = decoder.decode(awv.getF_awl_prizename());
			decode = new String(bytes, "UTF-8");
			encode = encoder.encodeToString(decode.getBytes());
		} catch (Exception e1) {
			LOG.error("isBase64-e:"+e1.getMessage());
		}
		if(encode.equals(awv.getF_awl_prizename())){//已加密数据
			if(decode.indexOf("<>")!=-1){
				String []decodes=decode.split("<>");
				awv.setF_awl_prizename(decodes[0]);
				awv.setF_awl_username(decodes.length>1?encoder.encodeToString(decodes[1].getBytes()):"");
				awv.setF_awl_useraddress(decodes.length>2?encoder.encodeToString(decodes[2].getBytes()):"");
			}
		}else{//未加密数据

		}
		return awv;
	}
	public List<AcWinningVo> selectWinningList(AcWinningVo awv) {
		List<AcWinningVo> results = activityDao.selectWinningList(awv);
		for (int i = 0; i < results.size(); i++) {
			if(results.get(i).getF_awl_serverid()==null||"".equals(results.get(i).getF_awl_serverid())) {

			}else {
				String serverid = results.get(i).getF_awl_serverid().substring(0,4)+"***"+
						results.get(i).getF_awl_serverid().substring(results.get(i).getF_awl_serverid().length()-4,results.get(i).getF_awl_serverid().length());
				results.get(i).setF_awl_serverid(serverid);
			}
		}
		return results;
	}

	public List<AcWinningVo> selectUWinningList(AcWinningVo awv) {
		List<AcWinningVo> results = activityDao.selectUWinningList(awv);
		for (int i = 0; i < results.size(); i++) {
			if(results.get(i).getF_awl_serverid()==null||"".equals(results.get(i).getF_awl_serverid())) {

			}else {
				String serverid = results.get(i).getF_awl_serverid().substring(0,4)+"***"+
						results.get(i).getF_awl_serverid().substring(results.get(i).getF_awl_serverid().length()-4,results.get(i).getF_awl_serverid().length());
				results.get(i).setF_awl_serverid(serverid);
			}
		}
		return results;
	}

	public int selectGameCount(AcGameVo agv) {
		int results = activityDao.selectGameCount(agv);
		return results;
	}

	public int insertGameList(AcGameVo agv) {
		int flag = 0;
		if(agv==null) {
			flag = -1;
		}
		if(flag ==0) {
			activityDao.insertGameList(agv);
			return 1;
		}
		return flag;
	}

	public List<AcRecordVo> selectRecordList(AcRecordVo arv){
		AcRecordVo RecordVo = new AcRecordVo();
		List<AcRecordVo> results = activityDao.selectRecordList(arv);
		return results;
	}

	public int selectRecordDDp(AcRecordVo arv) {
		int results = activityDao.selectRecordddp(arv);
		return results;
	}
	public int selectRecordLLk(AcRecordVo arv) {
		int results = activityDao.selectRecordllk(arv);
		return results;
	}
	public int selectRecordCount(AcRecordVo arv) {
		int results = activityDao.selectRecordCount(arv);
		return results;
	}
	public int  getTotalScore(AcRecordVo arv){
		return  activityDao.selectTotalScore(arv);
	}
	public int insertUserMessage(AcRecordVo arv) {
		int flag = 0;
		if(arv==null) {
			flag = -1;
		}
		if(flag ==0) {
			activityDao.insertUserMessage(arv);
			return 1;
		}
		return flag;
	}


	public int updateRecord_phone(AcRecordVo arv) {
		int flag = 0;
		if(arv==null) {
			flag = -1;
		}
		if(flag ==0) {
			flag = activityDao.updateRecord_phone(arv);
		}
		return flag;
	}

	public int updateRecords(AcRecordVo arv) {
		int flag = 0;
		if(arv==null) {
			flag = -1;
		}
		if(flag ==0) {
			flag = activityDao.updateRecords(arv);
		}
		return flag;
	}
	public int selectWinningDateCount(AcWinningVo awv) {
		int results = activityDao.selectWinningDateCount(awv);
		return results;
	}
	public List<AcWinningVo> selectWinningList2(AcWinningVo awv) {
		AcWinningVo acWinningVo=new AcWinningVo();
		List<AcWinningVo> results = activityDao.selectWinningList2(awv);
		return results;
	}

	public Map<String, Object> acHotelWinning(int f_aca_id,HttpServletRequest request) {
		int flag = 0;
		String message = "";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			AcContentActionVo acContentActionVo = activityModelDao.selectActivity(f_aca_id+"");
			int winningProbability = acContentActionVo.getF_aca_count();//中奖概率 单位%
			int winningTime = acContentActionVo.getF_aca_limit();//中奖有效时间 单位 小时

			HttpSession session = request.getSession();
			String userid= String.valueOf( session.getAttribute(SessionKey.SESSION_SERVERID));
			Date date = new Date();
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time1 = sdf1.format(date);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			String time2 = sdf2.format(date);
			AcLotteryVo alv = new AcLotteryVo();
			alv.setF_all_activityid(f_aca_id+"");
			alv.setF_all_date(time2);
			alv.setF_all_serverid(userid);
			int activityUserCount=activityDao.selectLotteryCount(alv);//今日已抽奖次数
			LOG.debug("今日已抽奖次数："+activityUserCount);
			if(activityUserCount<3){
				AcLotteryVo alvo = new AcLotteryVo();
				AcWinningVo awv = new AcWinningVo();
				awv.setF_awl_activityid(f_aca_id+"");
				awv.setF_awl_serverid(userid);
				awv.setF_awl_date(time2);
				int winningCount = activityDao.selectWinningCount(awv);//查询今日是否已中奖
				LOG.debug("今日中奖次数："+winningCount);
				if(winningCount==0){
					//double ran = 100 * Math.random();
					SecureRandom random = new SecureRandom();
					double ran = 100 * random.nextDouble();
					LOG.debug("中奖率："+ran+"："+winningProbability);
					if(ran<winningProbability){//中奖
						alvo.setF_all_order(1);
						String areaProbabilityJson = acContentActionVo.getF_aca_url();//各地区概率
						JSONArray areaProbabilityArr = (JSONArray) JSONArray.parse(areaProbabilityJson);
						int areaid= Integer.parseInt(String.valueOf( session.getAttribute(SessionKey.SESSION_AREA)));
						String areaProbability = areaProbabilityArr.getString(areaid-570);
						LOG.debug(areaProbability);
						String[] probabilityArr = areaProbability.split("\\\"");
						String[] probability = probabilityArr[3].split(",");
						int probability1 = Integer.parseInt(probability[0]);
						int probability2 = Integer.parseInt(probability[1]);

						List<ActivityAwardVo> aavList = activityDao.selectActivityAward(f_aca_id);//查询奖品列表
						//double ran2 = 100 * Math.random();
						double ran2 = 100 * random.nextDouble();
						AcWinningVo acWinningVo = new AcWinningVo();
						acWinningVo.setF_awl_serverid(userid);
						acWinningVo.setF_awl_activityid(f_aca_id+"");
						acWinningVo.setF_awl_date(time1);
						long currentTime = System.currentTimeMillis() + winningTime * 60 * 60 * 1000;
						Date date1 = new Date(currentTime);
						acWinningVo.setF_awl_endtime(sdf1.format(date1));
						LOG.debug("中奖等级："+ran2);
						if(probability.length==2){
							if(0<=ran2&&ran2<probability1){//一等奖
								flag = 1;
								acWinningVo.setF_awl_prizeid(aavList.get(0).getF_aoa_idou()+"");
								acWinningVo.setF_awl_prizename(aavList.get(0).getF_aoa_comment());
								acWinningVo.setF_awl_userphone(aavList.get(0).getF_aoa_awardid()+"");
								map.put("price", aavList.get(0).getF_aoa_idou());
								message = "中奖："+aavList.get(0).getF_aoa_comment();
								LOG.debug("中奖：获得"+aavList.get(0).getF_aoa_comment());
							}else{//二等奖
								flag = 2;
								acWinningVo.setF_awl_prizeid(aavList.get(1).getF_aoa_idou()+"");
								acWinningVo.setF_awl_prizename(aavList.get(1).getF_aoa_comment());
								acWinningVo.setF_awl_userphone(aavList.get(1).getF_aoa_awardid()+"");
								map.put("price", aavList.get(1).getF_aoa_idou());
								message = "中奖："+aavList.get(1).getF_aoa_comment();
								LOG.debug("中奖：获得"+aavList.get(1).getF_aoa_comment());
							}
						}else if(probability.length==3){
							if(0<=ran2&&ran2<probability1){//一等奖
								flag = 1;
								acWinningVo.setF_awl_prizeid(aavList.get(0).getF_aoa_idou()+"");
								acWinningVo.setF_awl_prizename(aavList.get(0).getF_aoa_comment());
								acWinningVo.setF_awl_userphone(aavList.get(0).getF_aoa_awardid()+"");
								map.put("price", aavList.get(0).getF_aoa_idou());
								message = "中奖："+aavList.get(0).getF_aoa_comment();
								LOG.debug("中奖：获得"+aavList.get(0).getF_aoa_comment());
							}else if(ran2>(probability1+probability2)){//三等奖
								flag = 3;
								acWinningVo.setF_awl_prizeid(aavList.get(2).getF_aoa_idou()+"");
								acWinningVo.setF_awl_prizename(aavList.get(2).getF_aoa_comment());
								acWinningVo.setF_awl_userphone(aavList.get(2).getF_aoa_awardid()+"");
								map.put("price", aavList.get(2).getF_aoa_idou());
								message = "中奖："+aavList.get(2).getF_aoa_comment();
								LOG.debug("中奖：获得"+aavList.get(2).getF_aoa_comment());
							}else{//二等奖
								flag = 2;
								acWinningVo.setF_awl_prizeid(aavList.get(1).getF_aoa_idou()+"");
								acWinningVo.setF_awl_prizename(aavList.get(1).getF_aoa_comment());
								acWinningVo.setF_awl_userphone(aavList.get(1).getF_aoa_awardid()+"");
								map.put("price", aavList.get(1).getF_aoa_idou());
								message = "中奖："+aavList.get(1).getF_aoa_comment();
								LOG.debug("中奖：获得"+aavList.get(1).getF_aoa_comment());
							}
						}
						activityDao.insertWinningList(acWinningVo);
					}else{
						alvo.setF_all_order(0);//0 未中奖 1中奖
						flag = 0;
						message = "很遗憾，未中奖！";
						LOG.debug("很遗憾，未中奖！");
					}
				}else{
					alvo.setF_all_order(0);//0 未中奖 1中奖
					flag = 0;
					message = "很遗憾，未中奖！";
					LOG.debug("今日已中奖");
				}
				//插入抽奖信息
				alvo.setF_all_activityid(f_aca_id+"");
				alvo.setF_all_date(time1);
				alvo.setF_all_serverid(userid);
				activityDao.insertLottery(alvo);
			}else{
				flag = -1;
				message = "已无次数";
				LOG.debug("已无次数");
			}
		} catch (Exception e) {
			LOG.error("抽奖出错",e);
		}

		map.put("flag", flag);
		map.put("message", message);

		return map;
	}

	public List<AcWinningVo> selectWinningList3(AcWinningVo awv) {
		List<AcWinningVo> results = activityDao.selectWinningList3(awv);
		return results;
	}
	/**
	 * @Description: 双扣抽奖活动
	 * @Param: * 用户id，活动id
	 * @return: map(" result ", " 结果 ") 结果：1.tomorrow 2.
	 * @Author: LiuL
	 * @Date: 2019/3/20
	 */
	public Map<String, String> Lott(AcLotteryVo alv, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		Map<String, String> map = new HashMap<String, String>();
		String userID = String.valueOf(session.getAttribute(SessionKey.SESSION_SERVERID));
		AcWinningVo awv = new AcWinningVo();
		int count = 0;//抽奖次数
		int usedCount = 0;//已经用过的抽奖机会
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time1 = sdf.format(date);
		String time2 = time1.substring(0, 10);
		alv.setF_all_date(time2);
		//随机生成票数 10，50，100
		//int rand = (int) (Math.random() * 3);
		SecureRandom random = new SecureRandom();
		int rand = (int)(3 * random.nextDouble());
		int arr[] = {10, 50, 100};
		Integer orderCount = getOrderCount(userID,request, response);//获取到的抽奖次数
		//抽奖获取的点赞票数
		ActivityVoteUserVo voteUserVo = new ActivityVoteUserVo();
		voteUserVo.setF_avu_serverid(userID);
		voteUserVo.setF_avu_contentid(1);
		voteUserVo.setF_avu_activityid(alv.getF_all_activityid());
		voteUserVo.setF_avu_source(0);
		voteUserVo.setF_avu_obligate1(0);
		voteUserVo.setF_avu_obligate2("点赞票数");
		voteUserVo.setF_avu_cdate(time1);
		alv.setF_all_date(time1);
		alv.setF_all_serverid(userID);
		Integer order = getOrder(userID,request,response);
		if (order == 1) {//订购过
			if (orderCount>0) {//可抽过奖
				insertLottery(alv);//插入信息到记录抽奖信息表
				awv.setF_awl_serverid(userID);
				awv.setF_awl_userphone(alv.getF_all_userphone());
				awv.setF_awl_activityid(alv.getF_all_activityid());
				awv.setF_ui_resolution(Integer.valueOf((String) session.getAttribute("SESSION_EPG_RESOLUTION")));
				awv.setF_awl_date(time1);
				Map<String, String> results = getLotteryResult(awv);//获取抽奖结果
				map = results;
				if (results.get("result").equals("0")) {//插入中奖信息
					awv.setF_awl_prizeid(results.get("awardId"));
					awv.setF_awl_prizename(results.get("awardName"));
					insertWinningList(awv);
					map.put("lottery", results.get("awardId"));
				} else {//没中奖给的抽奖票
					map.put("note", String.valueOf(arr[rand]));// 没中奖给100/200票
					voteUserVo.setF_avu_votenum(arr[rand]);
					voteUserVo.setF_avu_type(3);
					voteUserVo.setF_avu_memo("边锋福利专区赠送票数");
					acIntegralDao.insertACLikeVote(voteUserVo);
				}
			} else {//已经超过抽奖次数
				map.put("lottery", "tomorrow");//明天再试
			}
		} else {//未订购用户
			map.put("result", "10");//不中奖标识
			if (usedCount < count) {
				insertLottery(alv);//插入信息到记录抽奖信息表
				voteUserVo.setF_avu_votenum(arr[rand]);
				voteUserVo.setF_avu_type(3);
				voteUserVo.setF_avu_memo("福利专区抽奖赠送票数");
				acIntegralDao.insertACLikeVote(voteUserVo);
				map.put("note", String.valueOf(arr[rand]));//不再抽中给票
			} else {
				map.put("lottery", "tomorrow");//明天再试
			}
		}
		return map;
	}

	/**
	 * 查询是否订购
	 */
	public Integer getOrder(String userid,HttpServletRequest request, HttpServletResponse response) {
		int order = 0;
		Map<String, Object> json = epgCoService.getOrderType(userid,request, response);
		if (json.get("result") == "0") {
			return 1;
		} else {
			return order;
		}
	}

	/**
	 *  查询边锋订购的产品次数
	 *
	 */
	public Integer getOrderCount(String userid,HttpServletRequest request,HttpServletResponse response){
		int kidtotal = 0, NBAtotal = 0, YC = 0, nba = 0, serialAndFilmtotal = 0, movietotal = 0, serialtotal = 0, alltotal = 0;
		Map<String,Object> json = epgCoService.getOrderType(userid,request,response);
		if (json.get("result") == "0") {//判断是否订购
			if (json.get("kid_month") == "0" || json.get("kid_ThirdLine") == "0") {//少儿包月
				kidtotal = 2;
			}
			if (json.get("nba_yc") == "0") {//NBA+英超
				NBAtotal = 0;
			} else {
				if (json.get("yc_month") == "0") {//英超
					YC = 0;
				} else if (json.get("yc_ThirdLine") == "0") {
					YC = 0;
				}
				if (json.get("nba_ThirdLine") == "0") {
					nba = 0;
				} else if (json.get("nba_month") == "0") {
					nba = 0;
				}
			}
			if (json.get("mtv_month") == "0" || json.get("mtv_ThirdLine") == "0") {//影视
				serialAndFilmtotal = 3;
			} else {
				if (json.get("mv_month") == "0" || json.get("mv_ThirdLine") == "0") {//电影
					movietotal = 1;
				}
				if (json.get("tv_ThirdLine") == "0" || json.get("tv_month") == "0") {//电视剧
					serialtotal = 1;
				}
			}
			alltotal = kidtotal + NBAtotal + YC + nba + serialAndFilmtotal + movietotal + serialtotal + 3;
			if(json.get("filmAll") == "0") {
				alltotal = 8;
			}
		} else {
			alltotal = 3;
		}
		return alltotal;
	}

	/**
	 *
	 *  存取戏曲用户的答题信息
	 *
	 * */
	public Integer insertOpera(AcRecordVo arv,HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
		String userID = String.valueOf(session.getAttribute(SessionKey.SESSION_SERVERID));
		Date date=new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time1 = sdf.format(date);
		String time2 = time1.substring(0, 10);
		arv.setX_lwj_uesr_id(userID);
		arv.setX_lwj_activityid("戏曲专题");
		arv.setX_lwj_date(time1);
		arv.setX_lwj_ycjcs(1);
		arv.setX_lwj_zcjcs(1);
		arv.setX_lwj_order(1);
		arv.setX_lwj_yyxcs(1);
		int flag = 0;
		if(arv==null) {
			flag = -1;
		}
		if(flag ==0) {
			activityDao.insertUserMessage(arv);
			return 1;
		}
		return flag;

	}

	/**
	 *  查询用户的答题结果展示到页面
	 * */
	public List<AcRecordVo> getInfoOpera(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		String userID = String.valueOf(session.getAttribute(SessionKey.SESSION_SERVERID));
		AcRecordVo arv=new AcRecordVo();
		arv.setX_lwj_activityid("戏曲专题");
		arv.setX_lwj_uesr_id(userID);
		List<AcRecordVo> acRecordVos = activityDao.selectRecordList(arv);
		return acRecordVos;
	}
	/**
	 * @Description: 查询某一时间段内的抽奖次数
	 * @Param:  * @param null
	 * @return:
	 * @Author: LiuL
	 * @Date: 2019/6/17
	 */
	public int selectLottCount(AcLotteryVo alv,String starttime,String endtime) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("starttime",starttime);
		map.put("endtime",endtime);
		map.put("f_all_serverid",alv.getF_all_serverid());
		map.put("f_all_activityid",alv.getF_all_activityid());
		int results = activityDao.selectLottCount(map);
		return results;
	}

	public int selectAlwaysAwardInfo(AcLotteryVo alv)
	{
		Map<String, Object> map = new HashMap();
		map.put("f_all_serverid", alv.getF_all_serverid());
		map.put("f_all_activityid", alv.getF_all_activityid());

		int results = this.activityDao.selectAlwaysAwardINFo(map);
		return results;
	}
	public List<AcWinningVo> selectWinningListLimit(AcWinningVo awv) {
		AcWinningVo acWinningVo=new AcWinningVo();
		Map<String, Object> map = new HashMap();
		List<AcWinningVo> results = activityDao.selectWinningListLimit(awv);
		return results;
	}
	public Map<String, String> lotteryResult(AcLotteryVo alv, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		AcWinningVo awv = new AcWinningVo();
		int countLottery = 0;//抽奖次数
		String lottId = alv.getF_all_activityid();//抽奖id
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time1 = sdf.format(date);
		String time2 = time1.substring(0, 10);
		HttpSession session = request.getSession();
		String userID = String.valueOf(session.getAttribute(SessionKey.SESSION_SERVERID));
		String tokenkey = HappyAction.token(userID);
		String attribute = String.valueOf( session.getAttribute("EPGverify"+userID));
		if (attribute=="null" || !attribute.equals(tokenkey)) {
			LOG.debug("恶意攻击接口,session未获取到EPGverify:" + attribute);
			map.put("lottery", "tomorrow");//明天再试
			return map;
		}
		if (alv.getF_all_order() == 1) {//订购
			alv.setF_all_date(time2);
			if(alv.getF_all_activityids() != null && !"".equals(alv.getF_all_activityids())){
				alv.setF_all_activityid(alv.getF_all_activityids());
			}
			countLottery = selectLotteryCount(alv);//获取抽奖次数
			String number = String.valueOf(request.getParameter("LotteryNumber"));//LotteryNumber新增活动每次抽奖次数
			number=!isNumeric(number)?"1":number;
			if (countLottery < Integer.valueOf(number)) {//未抽过奖
				alv.setF_all_date(time1);
				alv.setF_all_activityid(lottId);
				insertLottery(alv);//插入抽奖信息
				awv.setF_awl_serverid(userID);
				awv.setF_awl_userphone(alv.getF_all_userphone());
				awv.setF_awl_activityid(lottId);
				awv.setF_ui_resolution(Integer.valueOf((String) session.getAttribute("SESSION_EPG_RESOLUTION")));
				awv.setF_awl_date(time1);
				Boolean isBlack=false;
				if(alv.getIsBlack()!=null&&"1".equals(alv.getIsBlack())){//此用户不可抽奖
					isBlack=true;
				}else{
					int i = selectAlwaysAwardInfo(alv);
					isBlack=i>0?true:isBlack;//在黑名单里 //过滤历史中奖专业户账号
				}
				if(!isBlack){//isBlack=false 不是黑名单用户
					LOG.debug("进入抽奖userID："+userID);
					Map<String, String> results = getLotteryResult(awv);//获取抽奖结果
					map = results;
					if(null != results.get("result") && results.get("result").equals("0")){//插入中奖信息
						awv.setF_awl_prizeid(results.get("awardId"));
						awv.setF_awl_prizename(results.get("awardName"));
						insertWinningList(awv);
						map.put("lottery", results.get("awardId"));
					}else{
						map.put("result", "-1");//没中奖
					}
				}else{
					LOG.debug("不中奖userID:"+userID);
					map.put("result", "-1");//没中奖
				}
			} else {//抽过奖
				map.put("lottery", "tomorrow");//次数用完的
			}
		}
		return map;
	}
	public Map<String, Object> syncIPTV(HttpServletRequest request,String syncJson,Map<String, String> lottResultMap,String lottId,String iptvAccount){
		JSONObject syncJsonObject = JSONObject.parseObject(syncJson);
		Map<String, Object> syncMap = new HashMap<String, Object>();
		if(lottResultMap.get("lottery")!=null &&  "tomorrow".equals(lottResultMap.get("lottery"))){
			return syncMap;
		}
		/*
		{
			"sync_prizeIds": ["176", "175", "174", "173"],
			"sync_goodsCodes": ["250006091397", "250006092624", "250006094668", "250006098418"],
			"sync_TVDOU_prizeIds": ["177", "-1"],
			"sync_TVDOU_num": ["100", "10"],
			"activityCode": "category_code_2001",
			"extraCode": "item_code_200101",
			"remark": "iptvLottery"
		}
    	*/
		//String str="{\"sync_prizeIds\":[\"176\",\"175\",\"174\",\"173\"],\"sync_goodsCodes\":[\"250006091397\",\"250006092624\",\"250006094668\",\"250006098418\"],\"sync_TVDOU_prizeIds\":[\"177\",\"-1\"],\"sync_TVDOU_num\":[\"100\",\"10\"],\"activityCode\":\"category_code_2001\",\"extraCode\":\"item_code_200101\",\"remark\":\"iptvLottery\"}";
		JSONArray  sync_prizeIds = syncJsonObject.getJSONArray("sync_prizeIds");
		JSONArray  sync_goodsCodes = syncJsonObject.getJSONArray("sync_goodsCodes");
		JSONArray  sync_TVDOU_prizeIds = syncJsonObject.getJSONArray("sync_TVDOU_prizeIds");
		JSONArray  sync_TVDOU_num = syncJsonObject.getJSONArray("sync_TVDOU_num");
		String  tvdou_activityId = syncJsonObject.getString("tvdou_activityId");
		String goodsCode="";
		String TVDOU_num="";
		if(sync_prizeIds!=null && sync_prizeIds.size()>0 && lottResultMap.get("lottery")!=null){//可以进行实物同步
			for(int i=0;i<sync_prizeIds.size();i++){
				if(sync_prizeIds.getString(i).equals(lottResultMap.get("lottery"))){
					goodsCode=sync_goodsCodes.getString(i);
					break;
				}
			}
		}
		if(sync_TVDOU_prizeIds!=null && sync_TVDOU_prizeIds.size()>0  && lottResultMap.get("result")!=null){//可以进行tv豆同步
			for(int i=0;i<sync_TVDOU_prizeIds.size();i++){
				if(sync_TVDOU_prizeIds.getString(i).equals(lottResultMap.get("result"))){
					TVDOU_num=sync_TVDOU_num.getString(i);
					break;
				}else if (lottResultMap.get("lottery")!=null && sync_TVDOU_prizeIds.getString(i).equals(lottResultMap.get("lottery"))){
					TVDOU_num=sync_TVDOU_num.getString(i);
					break;
				}
			}
		}
		if(!"".equals(goodsCode)){//实物同步
			syncMap = iptvServiceBean.addAward(iptvAccount,lottId,goodsCode);
		}
		if(lottResultMap.get("result")!=null && !"-1".equals(lottResultMap.get("result")) && lottResultMap.get("awardName").indexOf("TV豆") == -1 ){//未中奖时 如果奖品名称中没有 TV豆 则不同步 
			TVDOU_num="";
		}
		if(!"".equals(TVDOU_num)){//tv豆同步
			syncMap = iptvServiceBean.pointsProduce(iptvAccount,syncJsonObject.getString("activityCode"),
					syncJsonObject.getString("extraCode"),syncJsonObject.getString("remark"),Integer.parseInt(TVDOU_num),lottId);
			if("-1".equals(lottResultMap.get("result"))){//未中奖送tv豆 需入库
				AcWinningVo awv =new AcWinningVo();
				awv.setF_awl_prizeid(lottResultMap.get("result"));
				awv.setF_awl_prizename(TVDOU_num+"TV豆");
				awv.setF_awl_activityid(tvdou_activityId);
				awv.setF_awl_serverid(iptvAccount);
				HttpSession session = request.getSession();
				awv.setF_ui_resolution(Integer.valueOf((String) session.getAttribute("SESSION_EPG_RESOLUTION")));
				Date date=new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time1 = sdf.format(date);
				awv.setF_awl_date(time1);
				insertWinningList(awv);
			}
		}
		return syncMap;
	}
	/**
	 * @param str
	 * @return 判断是否为数字
	 */
	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0; ) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}
}
